package com.estronger.shopmanage.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.dingyg.updateutil.CustomDialog;
import com.dingyg.updateutil.IntranetUpdateManager;
import com.dingyg.updateutil.UpdateApp;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.MainGridAdapter;
import com.estronger.shopmanage.adapter.MainListAdapter;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B8Wether;
import com.estronger.shopmanage.bean.B9Share;
import com.estronger.shopmanage.bean.GridItemBean;
import com.estronger.shopmanage.bean.MenuPermission;
import com.estronger.shopmanage.bean.SoftwareUpdateInfo;
import com.estronger.shopmanage.ui.home.ShareArticleActivity;
import com.estronger.shopmanage.ui.home.presenter.IMainView;
import com.estronger.shopmanage.ui.home.presenter.MainPresenter;
import com.estronger.shopmanage.ui.home.WebActivity;
import com.estronger.shopmanage.ui.personal.PersonalActivity;
import com.estronger.shopmanage.utils.ActivityUtils;
import com.estronger.shopmanage.utils.DataTools;
import com.estronger.shopmanage.view.CustomGlridView;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.soonfor.evaluate.activity.EvaluateRankingActivity;
import com.soonfor.evaluate.activity.Evaluate_CustomersToMeActivity;
import com.soonfor.evaluate.activity.Evaluate_IToCustomersActivity;
import com.soonfor.evaluate.bean.EvaluateRankingBean;
import com.soonfor.evaluate.tools.ComToast;
import com.soonfor.evaluate.tools.ImageUtils;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AppDialog;
import com.estronger.shopmanage.view.RoundImageView;
import com.soonfor.evaluate.tools.Tokens;
import com.soonfor.evaluate.view.ClientEvalToMeView;
import com.soonfor.evaluate.view.MeEvaluateRankView;
import com.soonfor.systemcodes.SystemCodePresenter;
import com.soonfor.systemcodes.SystemCodes;
import com.tencent.external.tmselfupdatesdk.ITMSelfUpdateListener;
import com.tencent.external.tmselfupdatesdk.YYBDownloadListener;
import com.tencent.external.tmselfupdatesdk.model.TMSelfUpdateUpdateInfo;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jesse.nativelogger.NLogger;

public class MainActivity extends Activity implements IMainView {

    private MainPresenter presenter;
    @BindView(R.id.main_photo)
    RoundImageView imgfHead;
    @BindView(R.id.main_back_img)
    ImageView iv_backImg;
    @BindView(R.id.main_temper_img)
    ImageView iv_temper_img;
    @BindView(R.id.main_location)
    TextView tv_location;
    @BindView(R.id.main_temper)
    TextView tv_temper;
    @BindView(R.id.main_temper_state)
    TextView tv_state;
    @BindView(R.id.main_temper_wether)
    TextView tv_wether;

    @BindView(R.id.view_ClientEvalToMe)
    ClientEvalToMeView viewCETMe;//客户对我的评价
    @BindView(R.id.viewEvaluateRankView)
    MeEvaluateRankView evaluateRankView;//评价排行榜
    @BindView(R.id.llfToEvaluation_i_to_clients)
    LinearLayout llfToEvaluationIToClients;//我对客户的评价
    @BindView(R.id.tvfEvalNum)

    TextView tvfEvalNum;//我对客户的评价

    private String city = "定位中";
    private AMapLocationClientOption mLocationOption = null;
    private AMapLocationClient mLocationClient = null;
    private AlphaAnimation alpha;

    @BindView(R.id.gvbody)
    CustomGlridView gvbody;
    private MainGridAdapter gridAdapter;

    @BindView(R.id.mRecyclerArticle)
    RecyclerView mRecyArticle;
    private MainListAdapter adapter;
    private ArrayList<B9Share> shares;//分享文章集合
    private SystemCodePresenter scPresenter;

//    private UpdateManager updateManager;
//    private TMSelfUpdateManager tmSelfUpdateSDK;
    //官网
    private IntranetUpdateManager intUpdateManager;

    private  MenuPermission mpRight = null;//派工权限

    private String ifShowOtherPoint = "";//是否使用其他任务和客户评价功能

    private boolean ifReShow = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        QMUIStatusBarHelper.translucent(this);// 沉浸式状态栏
        initLocaleLanguage();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mpRight = null;
        ifReShow = false;
        //初始化更新sdk
//        tmSelfUpdateSDK = TMSelfUpdateManager.getInstance();
//        updateManager = UpdateManager.getInstance();
        //数夫官网更新
        String url_b = "http://www.soonfor.com/appdownload/homecase/apk/";
        String url[] = new String[]{ url_b + "version.txt", url_b};
        intUpdateManager = new IntranetUpdateManager(MainActivity.this, url);
        new Thread(checkSelfUpdateInt).start();
        try {
            presenter = new MainPresenter(this);
            initView();
            //注册极光
        } catch (Exception e) {
            NLogger.e("崩溃异常收集:" + e.getMessage());
        }
    }

    //获取系统参数
    private void getSystemCode() {
        if (scPresenter == null) {
            scPresenter = new SystemCodePresenter(new SystemCodePresenter.CallBack() {
                @Override
                public void onSingle(int type, boolean isSuccess, String data, String fullmsg) {}

                @Override
                public void onMult(boolean isSuccess, String fullmsg) {
                    String showOtherPoint = SystemCodes.getInstance().getDSM_IfShowOtherPoint();
                    if(showOtherPoint.equals("0")) {
                        if (!ifShowOtherPoint.equals("0")) {
                            ifShowOtherPoint = "0";
                            setOtherTaskView(0);
                        }
                    }else {
                        if (showOtherPoint.equals("")) {
                            SystemCodes.getInstance().setDSM_IfShowOtherPoint("1");
                        }
                        if(!ifShowOtherPoint.equals("1")) {
                            ifShowOtherPoint = "1";
                            presenter.addOtherTast();
                            gridAdapter.notifyDataSetChanged(presenter.getGridList());
                            setOtherTaskView(1);
                        }
                    }
                }
            });
        }
        scPresenter.getMultSystemParams(this, new String[]{Tokens.DSM_IFSHOWOTHERPOINT,
                Tokens.CRM_DLVISTMANCANSELMORE,
                Tokens.DSM_IfFinishCanUpdateAttaOnly,
                Tokens.DSM_IstFinishMustVideo,
                Tokens.DSM_FinishMustRemark
        });
    }

    // 初始化各个空间
    private void initView() {
        try {
            if (!PermissionUtils.isOPen(MainActivity.this)) {
                ComToast.showToast(this, "GPS开关未开启，无法正常定位！");
            }
            gridAdapter = new MainGridAdapter(this, presenter.getGridItemDatas());
            gvbody.setAdapter(gridAdapter);
            gvbody.setOnItemClickListener(itemListener);
            GridLayoutManager manager = new GridLayoutManager(this, 1);
            mRecyArticle.setLayoutManager(manager);
            adapter = new MainListAdapter(this);
            mRecyArticle.setAdapter(adapter);
        } catch (Exception e) {
            NLogger.e("崩溃异常收集:" + e.getMessage());
        }
        alpha = new AlphaAnimation(0, 1);
        alpha.setDuration(1500);
        alpha.setFillAfter(true);
        getSystemCode();
    }

    @Override
    protected void onResume() {
        try {
            MyApplication.mainActivity = this;
            presenter.getHeadPic(this, imgfHead);//获取头像
            if (mpRight == null) {
                presenter.getPgRifht(MainActivity.this);//获取显示权限
            } else {
                presenter.getTaskNums(MainActivity.this);//获取全部的任务数
            }
            new Thread(startLocate).start();
            if(ifReShow) {
                getSystemCode();
            }
        } catch (Exception e) {
            NLogger.e("崩溃异常收集:" + e.getMessage());
        }
        ifReShow = true;
        super.onResume();
    }

    private AdapterView.OnItemClickListener itemListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            GridItemBean gridItemBean = (GridItemBean) presenter.getGridList().get(position);
            if (gridItemBean.getM_class() != null) {
                Intent intent = new Intent(MainActivity.this, gridItemBean.getM_class());
                MainActivity.this.startActivity(intent);
            } else if (gridItemBean.get_id() == 11) {
                ImageUtils.sanBarCode(MainActivity.this);
            }
        }
    };

    /**
     * 刷新网格
     *
     * @param requestCode 请求代号
     * @param isSuccess   是否已成功
     */
    @Override
    public void refeshGrildView(int requestCode, boolean isSuccess, MenuPermission mpRight) {
        if(requestCode == 10001){//取权限
            this.mpRight = mpRight;
        }else if (requestCode == 10002) {//取数请求之后
            if (DataTools.rankingBeans != null && DataTools.rankingBeans.size() > 0) {
                if (shares == null) getShareArticles(0);
                presenter.getMyRanking();
            } else {
                presenter.getEvaluateOverview(MainActivity.this);
                if (shares == null) getShareArticles(1000);
            }
        }
        if (isSuccess) {
            gridAdapter.notifyDataSetChanged(presenter.getGridList());
        }
    }

    //获取分享文章
    private void getShareArticles(long time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                presenter.getShareArticles(MainActivity.this);
            }
        }, time);
    }

    //更新天气气温
    @Override
    public void refreshWeather(B8Wether weather) {
        try {
            if (weather != null) {
                tv_temper.setText(weather.getTemp1() + "~" + weather.getTemp2());
                tv_state.setText(weather.getWeather());
                tv_wether.setText(weather.getWd() + " " + weather.getWs());
                tv_location.setText(weather.getCity());
                iv_temper_img.setBackgroundResource(presenter.getWeatherDrawable(weather.getWeather()));
                iv_backImg.setAnimation(alpha);
                iv_backImg.setVisibility(View.VISIBLE);
                alpha.start();
            } else {
                tv_location.setText("");
            }
        } catch (Exception e) {
        }
    }

    //展示分享文章列表
    @Override
    public void showArticles(ArrayList<B9Share> dataList, boolean isSuccess) {
        shares = dataList;
        if (null != mRecyArticle) {
            if (isSuccess) {
                List<B9Share> result = new ArrayList<>();
                for (int i = 0; i < 5; i++) {
                    if (i < shares.size()) {
                        result.add(shares.get(i));
                    }
                }
                adapter.notifyDataSetChanged(result);
            }
        }
    }

    //展示待评价客户数量
    @Override
    public void showNoEvalCustomerNum(int stnum) {
        if (tvfEvalNum != null) tvfEvalNum.setText("待评价数：" + stnum);
    }

    @OnClick({R.id.main_photo, R.id.tv_personal_center, R.id.rlLookMoreShare, R.id.llfEvaluateToMe,
            R.id.llfToRanking, R.id.llfToEvaluation_i_to_clients})
    void ThisOnClick(View v) {
        switch (v.getId()) {
            case R.id.main_photo:
            case R.id.tv_personal_center:
                startActivity(new Intent(this, PersonalActivity.class));
                break;
            case R.id.rlLookMoreShare:
                Intent intent = new Intent(MainActivity.this, ShareArticleActivity.class);
                if (shares != null) {
                    intent.putParcelableArrayListExtra("SHARELIST", shares);
                }
                startActivity(intent);
                break;
            case R.id.llfEvaluateToMe:
                startActivity(new Intent(this, Evaluate_CustomersToMeActivity.class));
                break;
            case R.id.llfToRanking:
                startActivity(new Intent(this, EvaluateRankingActivity.class));
                break;
            case R.id.llfToEvaluation_i_to_clients:
                startActivity(new Intent(this, Evaluate_IToCustomersActivity.class));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == IntranetUpdateManager.INSTALL_PACKAGES_REQUESTCODE) {
            intUpdateManager.checkIsAndroid0();
        }else {
            String barcode = ImageUtils.getBarCodeContent(requestCode, resultCode, data);
            if (barcode == null || barcode.equals("")) {
                Toast.show(getApplicationContext(), "未能检测到二维码", 2000);
            } else {
                //判断url是否符合标准
                if (Patterns.WEB_URL.matcher(barcode).matches()) {
                    //符合标准
                    Intent intent = new Intent(this, WebActivity.class);
                    intent.putExtra("title", "");
                    intent.putExtra("url", barcode);
                    startActivity(intent);
                } else {
                    //不符合标准
                    Toast.show(MainActivity.this, "此条码内容不是标准的网址！", 2000);
                }
            }
        }
    }

    //刷新评价信息
    @Override
    public void setEvaluateInfoToView(final List<EvaluateRankingBean> rankingBeanList, final int ranking) {
        if (viewCETMe != null && ranking >= 0 && ranking < rankingBeanList.size()) {
            viewCETMe.initEvalToMeView(MainActivity.this, rankingBeanList.get(ranking));
        }
        if (evaluateRankView != null) {
            evaluateRankView.initEvaluateRankingView(MainActivity.this, rankingBeanList, ranking);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (null != mLocationClient)
            mLocationClient.stopLocation();
    }

    @Override
    protected void onDestroy() {
        if (DataTools.rankingBeans != null && DataTools.rankingBeans.size() > 0) {
            DataTools.rankingBeans.clear();
        }
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
//        if (tmSelfUpdateSDK != null) {
//            tmSelfUpdateSDK.destroy();
//        }
        super.onDestroy();
    }


    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.show(MainActivity.this, "再按一次退出程序",
                        1500);
                exitTime = System.currentTimeMillis();
            } else {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 500);

            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    //异步更新
    Runnable checkSelfUpdateRunnable = new Runnable() {
        @Override
        public void run() {
//            // 应用宝更新的逻辑
//            try {
//                Bundle bundle = null;//附加参数的bundle，一般情况下传空，可以由外部传入场景信息等，具体字段可参考 TMSelfUpdateConst. BUNDLE_KEY_* 的定义
//                tmSelfUpdateSDK.init(MyApplication.getApplication(), itmSelfUpdateSDKListener, getYYBListener, bundle);
//                tmSelfUpdateSDK.checkSelfUpdate();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }
    };

    Runnable startLocate = new Runnable() {
        @Override
        public void run() {
            if (PermissionUtils.isOPen(MainActivity.this)) {
                // 在主页时指定位一次
                if (TextUtils.isEmpty(MyApplication.city)) {
                    mLocationOption = new AMapLocationClientOption();
                    /*连续定位，一分钟一次*/
//                    mLocationOption.setOnceLocation(true);
                    /**
                     * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
                     */
                    mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
                    mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
                    mLocationOption.setNeedAddress(true);
                    try {
                        mLocationClient = new AMapLocationClient(getApplicationContext());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if(null != mLocationClient){
                        mLocationClient.setLocationOption(mLocationOption);
                        //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                        mLocationClient.stopLocation();
                        mLocationClient.startLocation();
                        mLocationClient.setLocationListener(mLocationListener);
                    }
                } else {
                    city = MyApplication.city;
                    if (TextUtils.isEmpty(MyApplication.cityID)) {
                        presenter.getCityCode(MainActivity.this);
                    } else {
                        presenter.getWeather();
                    }
                }
            }
        }
    };
    // 高德地图位置改变的监听
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    amapLocation.getCity(); // 获取城市
                    amapLocation.getCityCode();// 获取城市编码
                    amapLocation.getAdCode(); // 获取地区编码
                    MyApplication.latitude = amapLocation.getLatitude();
                    MyApplication.longitude = amapLocation.getLongitude();
                    MyApplication.address = amapLocation.getAddress();
                    MyApplication.province = amapLocation.getProvince();
                    String mCity = amapLocation.getCity();
                    if (mCity.length() > 2 && mCity.endsWith("市")) {
                        city = mCity.substring(0, mCity.length() - 1);
                        MyApplication.city = city;
                        presenter.getCityCode(MainActivity.this);
                    }
                    if (0 != MyApplication.latitude
                            && 0 != MyApplication.longitude) {
                        if (mLocationClient != null)
                            mLocationClient.stopLocation();
                    }
                } else {
                    NLogger.e("Main定位失败", amapLocation.getErrorInfo());
                }
            }
        }
    };

    private Dialog dialog;
    //自更新监听
    private ITMSelfUpdateListener itmSelfUpdateSDKListener = new ITMSelfUpdateListener() {
        @Override
        public void onDownloadAppStateChanged(int i, int i1, String s) {
        }

        @Override
        public void onDownloadAppProgressChanged(long l, long l1) {
        }

        @Override
        public void onUpdateInfoReceived(TMSelfUpdateUpdateInfo tmSelfUpdateUpdateInfo) {
            try {
                SoftwareUpdateInfo updateInfo = new SoftwareUpdateInfo();
                if (tmSelfUpdateUpdateInfo != null
                        && tmSelfUpdateUpdateInfo.getStatus() == TMSelfUpdateUpdateInfo.STATUS_OK
                        && tmSelfUpdateUpdateInfo.getNewApkSize() > 0) {
                    // 解析版本号
                    String url = tmSelfUpdateUpdateInfo.getUpdateDownloadUrl();
                    String version = "";
                    if (url != null && url.length() > 0) {
                        String[] temp = url.split("_");
                        if (temp.length > 2) {
                            version = temp[1];
                        }
                    }
                    updateInfo.hasNewVersion = true;
                    updateInfo.newVersion = version;
                    updateInfo.updateContent = tmSelfUpdateUpdateInfo.getNewFeature();
                    updateInfo.updateSize = tmSelfUpdateUpdateInfo.getNewApkSize();

                    //patch包大小：如果不为零则说明有增量包，否则说明只有全量包
                    updateInfo.patchSize = tmSelfUpdateUpdateInfo.getPatchSize();
                }
                Handler handler = new Handler();
                handler.getLooper();
                if (updateInfo.hasNewVersion) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            dialog = AppDialog.createUpdateDialog(MainActivity.this, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    dialog.setCancelable(true);
//                                    updateManager.CheckAndGetClick(MainActivity.this, null);
                                }
                            });
                            dialog.show();
                        }
                    });
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        }
    };
    private YYBDownloadListener getYYBListener = new YYBDownloadListener() {
        @Override
        public void onDownloadYYBStateChanged(String url, final int state, int errorCode, String errorMsg) {
            //TODO 应用宝下载状态变化的处理逻辑
        }

        @Override
        public void onDownloadYYBProgressChanged(final String url, final long receiveDataLen, final long totalDataLen) {
            //TODO 应用宝下载进度变化的处理逻辑
        }

        @Override
        public void onCheckDownloadYYBState(String s, int i, long l, long l1) {

        }
    };
    //内网更新
    Runnable checkSelfUpdateInt = new Runnable() {
        @Override
        public void run() {
            // TODO 这里写上传逻辑
            try {
                int localVerCode = intUpdateManager.getLocalVerCode();
                int serverVerCode = intUpdateManager.getServerVerCode();
                // 如果服务器版本高于本地版本则提示更新
                if (serverVerCode > localVerCode) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (ActivityUtils.isRunning(MainActivity.this)) {
                                if (System.currentTimeMillis() - UpdateApp.lastUpdateTime > 0) {
                                    UpdateApp.lastUpdateTime = System.currentTimeMillis();
                                    dialog = CustomDialog.createUpdateDialog(MainActivity.this,
                                            new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    dialog.dismiss();
                                                    dialog.setCancelable(true);
                                                    intUpdateManager.checkIsAndroid0();
                                                }
                                            }, null);
                                    dialog.show();
                                }
                            }
                        }
                    });
                }
            } catch (Exception e) {
            }
        }
    };

    private void initLocaleLanguage() {
        Resources resources = this.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = Locale.CHINA;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());//更新配置 }
    }

    public void setOtherTaskView(int visibile) {
        if (visibile == 1) {
            viewCETMe.setVisibility(View.VISIBLE);
            evaluateRankView.setVisibility(View.VISIBLE);
            llfToEvaluationIToClients.setVisibility(View.VISIBLE);
        }else {
            viewCETMe.setVisibility(View.GONE);
            evaluateRankView.setVisibility(View.GONE);
            llfToEvaluationIToClients.setVisibility(View.GONE);
        }
    }
}
